<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
use app\common\controller\IdexBaseController;
use app\index\model\UserModel;
use app\index\model\ComplainModel;
use app\index\model\MemberVerifModel;
use app\index\model\AgentModel;
use app\index\model\UnionModel;
use app\index\model\Qianyue;

class Member extends IdexBaseController
{
	//会员中心
    public function index()
    {
    	$info_user = session('info_user');
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	if($info_user && strlen($info_user['mobile'])<2){
    		$this->redirect('index/index/my_mobile');
    	}
    	
    	
    	$info_user['commission'] = substr($info_user['commission'],0,strlen($info_user['commission'])-2);
    	$info_user['balance'] 	 = substr($info_user['balance'],0,strlen($info_user['balance'])-2);
    	$info_user['score'] 	 = substr($info_user['score'],0,strlen($info_user['score'])-2);
    	
    	$this->assign('info_user',$info_user);
    	
       	return  $this->fetch();
    }
	public function step1(){
		$info_user = session('info_user');
		$where['user_id']=$info_user['id'];
		$res=db("agent_qianyue")->where($where)->find();
		$this->assign('qy',$res);
		if($res['state']==1){
			$agent=db("info_agent")->where("user_id",$info_user['id'])->find();
			$this->assign("agent",$agent);
			return  $this->fetch("agent");
		}else{
			return  $this->fetch();			
		}
	}
	public function step2(){
		$agent_type=input("agent_type");
		$info_user = session('info_user');
		$where['user_id']=$info_user['id'];
		$res=db("agent_qianyue")->where($where)->find();
		if($res){
			db("agent_qianyue")->where($where)->update(['agent_type'=>$agent_type]);
		}else{
			$data['user_id']=$info_user['id'];
			$data['agent_type']=$agent_type;
			db("agent_qianyue")->insert($data);
		}
		return  $this->fetch();
	}
	public function step3(){
		$info_user = session('info_user');
		$where['user_id']=$info_user['id'];
		if($_POST){
				$qy=db("agent_qianyue")->where($where)->find();
				$param['agent_name'] =input("agent_name1");
				$param['mobile']=input("contact_tel");
				$param['address'] =input("address");
				$param['user_id'] 		= $info_user['id'];
	    		$param['level1'] 		= $info_user['level'];
	    		$param['add_time'] 		= now_time();
	    		$param['oem_id'] 		= $info_user['oem_id'];
	    		$param['agency_id1'] 	= $info_user['agency_id1'];
	    		$param['agency_id2'] 	= $info_user['agency_id2'];
	    		$param['salesman_id'] 	= $info_user['salesman_id'];
	    		$param['password']		= md5_salt('123456');
	    		$param['operation_pwd'] = md5_salt('123456');
	    		$agent_model = new AgentModel();
	    		$agent=db("info_agent")->where("user_id",$info_user['id'])->find();
				if(!$agent){
					$result = $agent_model -> allowField(true)-> save($param);
					if($result){
						$agent=db("info_agent")->where("user_id",$info_user['id'])->find();
						$_POST['agent_id']=$agent['id'];
						db("info_user")->where("id",$info_user['id'])->update(["is_agent"=>1]);
					}
				}				
				$qianyue=new Qianyue();
				$res=$qianyue->allowField(true)->save($_POST,['user_id'=>$info_user['id']]);
				if($res){
					return json(['code'=>200,'msg'=>'保存成功']);
				}else{
					return json(['code'=>400,'msg'=>'保存失败']);
				}
		}
		$qy=db("agent_qianyue")->where($where)->find();
		$this->assign('qy',$qy);
		$typelist=db('sys_platform_type')->where('pid',0)->select();
		$this->assign('types',$typelist);	
		return  $this->fetch();
	}
	public function step4(){
		if($_POST){
				$info_user = session('info_user');
				$qianyue=new Qianyue();
				$res=$qianyue->allowField(true)->save($_POST,['user_id'=>$info_user['id']]);
				if($res){
					return json(['code'=>200,'msg'=>'保存成功']);
				}else{
					return json(['code'=>400,'msg'=>'保存失败']);
				}
		}
		$info_user = session('info_user');
		$qy=db('agent_qianyue')->where("user_id",$info_user['id'])->find();
		$this->assign('agent_type',$qy['agent_type']);
		$this->assign('qy',$qy);
		return  $this->fetch();
	}
	public function step5(){
			$info_user = session('info_user');
		if($_POST){
				$qianyue=new Qianyue();
				$res=$qianyue->allowField(true)->save($_POST,['user_id'=>$info_user['id']]);
				if($res){
					return json(['code'=>200,'msg'=>'保存成功']);
				}else{
					return json(['code'=>400,'msg'=>'保存失败']);
				}
		}
		$qy=db('agent_qianyue')->where("user_id",$info_user['id'])->find();
		$this->assign('qy',$qy);
		return  $this->fetch();
	}
	public function upload1(){
		include_once ('././vendor/aliyun-oss-php-sdk/autoload.php');
		$files = $_POST["value"];  
	    $tmp = base64_decode($files);  
	    $fn = time()."_".rand(100000, 999999) . ".jpg";
		$fp = './public/uploads/image/'. $fn;
		$fp1 = 'public/uploads/image/'. $fn;
	    $res=file_put_contents( $fp, $tmp);
		$ossClient = new \OSS\OssClient('LTAIaqGtJ3JDXJvv', 'Q2kTcyepAHX0VOR44OtszVoyOKE8gl', 'oss-cn-shanghai.aliyuncs.com');
		try{
			$res=$ossClient->uploadFile("long3",$fn,$fp1);
			$src='http://long3.oss-cn-shanghai.aliyuncs.com/'.$fn;
			unlink($fp1);
			return json(["code"=>200,'url'=>$src]);
		} catch(OssException $e) {
			return json(["code"=>404,'msg'=>'上传错误']);
		}  
		
	}
	public function step6(){
		$info_user = session('info_user');
		if($_POST){
				$qianyue=new Qianyue();
				$param=$_POST;
				$param['add_time']=now_time();
				$res=$qianyue->allowField(true)->save($param,['user_id'=>$info_user['id']]);
				if($res){
					$tem_w['title']='申请开店';
					$tem=db("sms_template")->where($tem_w)->find();
					$msg=sendsms($tem['sign_name'],config('send_mobile'),$tem['tid'],'code','有新',1);
					return json(['code'=>200,'msg'=>'提交成功等待审核']);
				}else{
					return json(['code'=>400,'msg'=>'保存失败']);
				}
		}
		$qy=db('agent_qianyue')->where("user_id",$info_user['id'])->find();
		$this->assign('qy',$qy);
		return  $this->fetch();
	}
	public function update_pwd(){
		if($_POST){
			$info_user = session('info_user');
			$where['id']=$info_user['id'];
			$where['password']=md5_salt(input("pwd"));
			$update['password']=md5_salt(input("pwd1"));
    		$res = db('info_user')->where($where)->update($update);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>400,'msg'=>'修改失败']);
			}
		}else{
				return  $this->fetch();
		}
	
	}
	//更多设置
	public function more(){
		return  $this->fetch();
	}
	public function about(){
		
			return  $this->fetch();
	}
	public function help(){
			return  $this->fetch();
	}
	public function help_show(){
			$help_id = request()->param('help_id');
		$detail = db('mall_helps')->where('pid',$help_id)->find();
		$detail['content'] = htmlspecialchars_decode($detail['content']);
		$this->assign('detail',$detail);
       	return  $this->fetch();
	}
	public function get_helps(){
		$auth_rule_list = db('mall_helptype')->order("id asc")->select();
        foreach ($auth_rule_list as $value) {
                $menu[] = $value;
        }
        $menu = !empty($menu) ? array2tree($menu) : [];

		if($menu){
			return json(['code'=>200,"data"=>$menu]);
		}else{
			return json(['code'=>405,"msg"=>'数据错误']);
		}	
	}
	//我的推广会员
    public function tglist(){
    	$info_user = session('info_user');
    	$list=db('info_user')->where('level',$info_user['id'])->field("user_name,mobile,score")->select();
		$this->assign('list',$list);
       	return  $this->fetch();
    }
    //会员资料
    public function member()
    {
    	$info_user = session('info_user');
    	
    	if(request()->isPost()){
    		$param=input('post.');
    		$user_model = new UserModel();
    		
    		$rest=$user_model->where('id',$info_user['id'])->update($param);
    		if($rest){
    			$this->success('修改成功');
			}else{
				$this->error('修改失败');
			}
    	}
    	
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	
    	$this->assign('info_user',$info_user);
       	return  $this->fetch();
    }
    //会员认证
    public function renzhen()
    {
    	$info_user = session('info_user');
    	if(request()->isPost()){
    		$param=input('post.');
    		$member_verif = new MemberVerifModel();
    		$param['user_id']	= $info_user['id'];
    		$verif_info = db('sys_member_verif')->where('user_id',$info_user['id'])->find();
    		if($verif_info){
    			$param['state']	= 2;
    			$result = $member_verif -> where('id',$verif_info['id']) -> update($param);
    		}else{
    			$param['add_time']	= now_time();
    			$param['oem_id']	= $info_user['oem_id'];
    			$result = $member_verif -> allowField(true)-> save($param);
    		}
    		if($result){
    			$this->success('成功');
			}else{
				$this->error('失败');
			}
    	}
    	
    	$verif_info = db('sys_member_verif')->where('user_id',$info_user['id'])->find();
    	$this->assign('verif_info',$verif_info);
       	return  $this->fetch();
    }
    
    
    //会员提现
    public function tixian()
    {
    	//获取oem信息
		$info_user = db('info_user')->where('id',session('info_user')['id'])->find();
		//获取用户认证信息
		$member_verif = Db::table('sys_member_verif')->where('user_type', 1)->where('user_id',$info_user['id'])->find();
		
		if(request()->isPost()){
			// 启动事务
			Db::startTrans();			
			try{
				//查询余额
				if(bccomp($info_user['balance'], $_POST['balance'], 4)>=0){
					//更新用户信息
					db('info_user')->where('id', $info_user['id'])->setDec('balance',$_POST['balance']);
					//oem余额变化日志
					balance_change($info_user['id'],0,1,$_POST['balance'],2,"余额提现",
					0,$info_user['oem_id'],$info_user['agency_id1'],$info_user['agency_id2']);
					
					
					//提现日志
					withdrawals_log($info_user['id'],1,$_POST['balance'],$_POST['balance'],0,1,"用户".$info_user['mobile']."提现".$_POST['balance'],
    0,0,0,0,$member_verif['bank_name'],$member_verif['bank_no'],$member_verif['user_name'],$member_verif['reserve_mobile'],$info_user['oem_id']);
					 
					// 提交事务
    				Db::commit();
					 
					return json(['code'=>200,'msg'=>'提交成功']);
				}else{
					return json(['code'=>402,'msg'=>'提交失败']);
				}
			}catch ( Exception $e ) {
			    //$e->getMessage();
			    //回滚
			    Db::rollback();
			    exit;
			}
		}
		
		
		$this->assign('info_user',$info_user);
		$this->assign('member_verif',$member_verif);
    	
      	return  $this->fetch();
    }
    
    
    //商家申请
    public function shenqing()
    {
    	$info_user = session('info_user');
    	
    	//获取用户详细信息
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
    	
    	if(request()->isPost()){
    		$param=input('post.');
    		$param['user_id'] 		= $info_user['id'];
    		$param['level1'] 		= $info_user['level'];
    		$param['add_time'] 		= now_time();
    		$param['oem_id'] 		= $info_user['oem_id'];
    		$param['agency_id1'] 	= $info_user['agency_id1'];
    		$param['agency_id2'] 	= $info_user['agency_id2'];
    		$param['salesman_id'] 	= $info_user['salesman_id'];
    		$param['password']		= md5_salt($param['password']);
    		$param['operation_pwd'] = md5_salt($param['operation_pwd']);
    		$agent_model = new AgentModel();
    		$result = $agent_model -> allowField(true)-> save($param);
    		if($result){
    			
    			//更新用户开店状态
    			Db::table('info_user')->where('id', $info_user['id'])->update(['is_agent' => 1]);
    			$this->success('申请成功');
			}else{
				$this->error('申请失败');
			}
    	}
        return  $this->fetch();
    }
    
    //联盟商圈
    public function union()
    {
    	$info_user = session('info_user');
    	
    	//查找当前用户是否已创建联盟
    	$union_agent =  db('union_agent')
    					->where('u_id',$info_user['id'])
    					->where('is_state',1)
    					->where('state',2)
    					->find();
    	if($union_agent){
    		$union_agent['is_create'] =1;
    		$this->assign('data',$union_agent);
    	}
    	if(request()->isPost()){
    		$param=input('post.');
    		$union_model = new UnionModel();
    		if($union_agent){
    			$result = $union_model -> allowField(true)->where('u_id',$info_user['id'])-> update($param);
    		}else{
    			$param['add_time'] 		= now_time();
    			$param['oem_id'] 		= $info_user['oem_id'];
    			$param['u_id'] 		= $info_user['id'];
    			$result = $union_model -> allowField(true)-> save($param);
    		}
    		if($result){
    			$this->success('成功');
			}else{
				$this->error('失败');
			}
    	}
    	return  $this->fetch();
    }
    
    
    //联盟成员
    public function union_memberlist()
    {
    	$where['u_id'] 	=  session('info_user')['id'];
    	$where['state'] =  ['in','1,2'];
    	$memberlist = db('union_member')->where($where)->select();
    	$this->assign('memberlist',$memberlist);
    	$this->assign('empty','<span class="empty">没有数据</span>');
        return  $this->fetch();
    }
    
    //移除成员
    public function yichu()
    {
    	$result = db('union_member')->where('id',input('id'))->delete();
    	if($result){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
    
    //审核成员
    public function membershenhe()
    {
    	$param['state'] = 1;
    	$result = db('union_member')->where('id',input('id'))->update($param);
    	if($result){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
    
    //积分记录
    public function score_record()
    {
    	$where['u_id'] 	=  session('info_user')['id'];
    	$loglist = db('log_user_score')->where($where)->order("add_time desc")->select();
    	$this->assign('loglist',$loglist);
    	$this->assign('empty','<span class="empty">没有数据</span>');
        return  $this->fetch();
    }
    
    //佣金记录
    public function yongj_record()
    {
    	$where['u_id'] 	=  session('info_user')['id'];
    	$loglist = db('log_user_commission')->where($where)->select();
    	$this->assign('loglist',$loglist);
    	$this->assign('empty','<span class="empty">没有数据</span>');
        return  $this->fetch();
    }
    
    //余额记录
    public function yue_record()
    {
    	$where['u_id'] 	=  session('info_user')['id'];
    	$loglist = db('log_user_charge')->where($where)->select();
    	$this->assign('loglist',$loglist);
    	$this->assign('empty','<span class="empty">没有数据</span>');
        return  $this->fetch();
    }
    
    //佣金转余额
    public function yongj_yue()
    {
    	$info_user = db('info_user')->where('id',session('info_user')['id'])->find();
    	
    	if(request()->isPost()){
    		// 启动事务
			Db::startTrans();
			try{
				//查询余额
				if(bccomp($info_user['commission'], $_POST['commission'], 4)>=0){
					//计算佣金转为余额的金额
					$change_val = bcsub($_POST['commission'], bcmul($_POST['commission'], 0.05, 4), 4);
					
					$new_commission = bcsub($info_user['commission'], $_POST['commission'], 4);
					$new_balance = bcadd($info_user['balance'],$change_val, 4);
					//更新用户信息
					db('info_user')->where('id', $info_user['id'])->update(['balance' => $new_balance,'commission'=>$new_commission]);
					//用户佣金变化日志
					user_commission_change($info_user['id'],0,5,$_POST['commission'],2,"佣金转余额扣除佣金",
					0,$info_user['oem_id'],$info_user['agency_id1'],$info_user['agency_id2']);
					//用户余额变化日志
					 user_money_change($info_user['id'],0,2,$change_val,1,"佣金转余额增加余额",
					 0,$info_user['oem_id'],$info_user['agency_id1'],$info_user['agency_id2']);
					// 提交事务
    				Db::commit();
					return json(['code'=>200,'msg'=>'提交成功']);
				}else{
					return json(['code'=>402,'msg'=>'提交失败']);
				}
			}catch ( Exception $e ) {
			    //$e->getMessage();
			    //回滚
			    Db::rollback();
			    exit;
			}
    	}
    	$this->assign('info_user',$info_user);
       	return  $this->fetch();
    }
    
    //意见反馈
    public function feedback()
    {
    	$info_user = session('info_user');
    	
    	if(request()->isPost()){
    		$param=input('post.');
    		
    		$sys_complain = new ComplainModel();
    		
    		$param['add_time'] = now_time();
    		$param['oem_id'] = $info_user['oem_id'];
    		
    		$rest=$sys_complain->allowField(true)->save($param);
    		if($rest){
    			$this->success('提交成功','index/member/index');
			}else{
				$this->error('提交失败');
			}
    	}
    	
       return  $this->fetch();
    }
    
    //推广中心
    public function friends()
    {	
    	$info_user = session('info_user');
    	
    	$info_user = db('info_user')->where('id',$info_user['id'])->find();
		$myfriends=db("info_user")->where("level",$info_user['id'])->count();
		$this->assign("counts",$myfriends);
    	
    	$where['u_id'] = $info_user['id'];
    	$where['operator'] = 1;
		$commission_income =db('log_user_commission')->where($where)->sum('balance');
    	
    	//二维码链接
    	$redirect_url="http://".$_SERVER['HTTP_HOST']."/index/index/regist?fromuid=".
    	$info_user['id']."&salesman_id=".$info_user['salesman_id'];
		
		$info_user['code_url'] = $redirect_url;
    	
    	//用户头像
    	$info_user['logo'] = strlen($info_user['logo'])>2?$info_user['logo']:"__PBULIC__/static/index/images/logo-ma.jpg";
    	
    	//累计佣金
    	$info_user['commission_income'] = substr($commission_income>0?$commission_income:"0.00",0,4);;
    	
    	$this->assign('info_user',$info_user);
    	
       	return  $this->fetch();
    }
    
     //积分充值
    public function charge_score()
    {
    	$user_info = session('info_user');
    	
    	$user_info = db('info_user')->where($user_info)->find();
    	
		$agent_info = db('info_agent')->where('user_id',$user_info['id'])->find();
		
		$agent_info['score'] = substr($agent_info['score'],0,4);
		
		$this->assign('user_info',$user_info);
    	$this->assign('agent_info',$agent_info);
    	
       return  $this->fetch();
    }
    
     //邀请商家入驻
    public function yaoqsjrz()
    {
    	//查找当前用户是否已创建联盟
    	$union_agent =  db('union_agent')
    					->where('u_id',session('info_user')['id'])
    					->where('is_state',1)
    					->where('state',2)
    					->find();
		    	
    	$this->assign('union_agent',$union_agent);
    	//二维码链接
    	$redirect_url="http://".$_SERVER['HTTP_HOST']."/index/member/union_join?union_id=".
    	$union_agent['id'];
    	
    	$union_agent['redirect_url'] = $redirect_url;
    	
    	$this->assign('union_agent',$union_agent);
    	
    	
       return  $this->fetch();
    }
    
    //商家入驻
    function union_join(){
    	
    	$union_agent =  db('union_agent')->where('id',input('union_id'))->find();
		
		$this->assign('union_agent',$union_agent);
		    	
    	return  $this->fetch();
    }
    
    //分享赚钱
    public function share_money()
    {
    	$user_info = session('info_user');
    	//获取当前用户信息
		$user_info = db('info_user')->where('id',$user_info['id'])->find();    	
    	$this->assign('user_info',$user_info);
       	return  $this->fetch();
    }
    
    //申请加入联盟商圈
    function add_union(){
    	$user_info = session('info_user');
    	//检查当前用户是否是商家
    	$agent_info = db('info_agent')->where('user_id',$user_info['id'])->find();
    	if($agent_info){
    		$union=Db::table('union_agent')->where('id',input('union_id'))->find();
    		$param['u_id']				= $agent_info['user_id'];
    		$param['union_id']			= $union['id'];
    		$param['agent_id']			= $agent_info['id'];
    		$param['store_name']		= $agent_info['agent_name'];
    		$param['thumb']				= $agent_info['logo'];
    		$param['lm_name']			= $union['name'];
    		$param['store_tel']			= $agent_info['mobile'];
    		$param['address']			= $agent_info['address'];
    		$param['customer_volume']	= 0;
    		$param['unnion_ads_money']	= 0.2;
    		$param['add_time']			= now_time();
    		$res = Db::table('union_member')->insert($param);
			if($res){
				return json(['code'=>200,'msg'=>'成功']);
			}else{
				return json(['code'=>403,'msg'=>'失败']);
			}
    	}else{
    		return json(['code'=>402,'msg'=>'请先申请成为商家']);
    	}
    }
    
}
